package com.xiaoyezi.demo2.Controller;



import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xiaoyezi.demo2.DataSource.User;
import com.xiaoyezi.demo2.base.Status;
import com.xiaoyezi.demo2.service.impl.UserService;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;



@RestController

@CrossOrigin(value = "http://localhost:1024",allowCredentials = "true")
public class userController {

    // 注入UserService
    @Autowired
    UserService userService;

    // 返回状态
    Status s = new Status();
    // 返回图片的url
    @PostMapping("/image")
    public Status fileUpload(@RequestParam("file") MultipartFile file,User user,HttpServletRequest request) {
        System.out.println("传输文件开始");
        // 判断接收的文件是否存在
        if (file.isEmpty()) {
            return s.error("图片上传失败1");
        }

        // 文件校验重命名（a:1.png  b:1.png）
        String originalFilename = file.getOriginalFilename(); // 原来的图片名
        String ext = "." + originalFilename.split("\\.")[1]; // 提取图片后缀并添加.(1.png)
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 新的图片名(bb06c72eb3dc4262935375c0f2678d62.jpg)
        String fileName = uuid + ext;

        // 文件的保存路径
        String uploadDir = "C:/Users/xyz34/Documents/java/java-springboot-project/demo2/src/main/resources/static/images";
        // 将文件的保存路径和新文件名组合起来，形成完整的文件路径
        String path = uploadDir + File.separator + fileName;
        // 在控制台打印出完整的文件路径，用于调试和确认文件将被保存的确切位置
        System.out.println(path);

        try {
            file.transferTo(new File(path));
            System.out.println("传输文件结束");
            // 返回HTTP URL
            String imageUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + fileName;
            // 将imageUrl存储到数据库中
            user.setImageAddress(imageUrl);
            userService.Update(user);
            // 查询数据并返回
            User getByIdImageAddress = userService.getById(user);
            return s.success(getByIdImageAddress);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.error("图片上传失败2");
    }


    // 更新用户
    @PostMapping("setUserData")
    public Status Update(@RequestBody User user){
        if (user == null){
            return s.error("请输入信息！");
        }
        User getId = userService.getById(user);
        if (getId ==null) {
            return s.error("请检查返回后段的数据");
        }else {
            userService.Update(user);
            User UpdaetGetId = userService.getById(user);
            return Status.success(UpdaetGetId);
        }
    }

    // 根据ID查询数据
    @PostMapping("getById")
    public Status getById(@RequestBody User user){
        User u = userService.getById(user);
        if (u == null){
            return s.error("账号不存在！");
        }else {
            return Status.success(u);
        }
    }

    // 根据zhanghao查询数据
    @PostMapping("getUserData")
    public Status getByZhanghao(@RequestBody User user){
        User u = userService.getByZhanghao(user);
        if (u == null){
            return s.error("账号不存在！");
        }else {
            return Status.success(u);
        }
    }
    
    // 创建用户
   @PostMapping("createUser") // POST请求
    public Status createUser(@RequestBody User user){
        if (user.getZhanghao() == null || user.getPassword() == null || user.getCategory() ==null){
            return s.error("信息不能为空!");
        }
        if (!user.getCategory().equals("用户") && !user.getCategory().equals("商家")){
            return s.error("请输入用户或商家！");
            
        }
        User showUser = userService.login(user);
        if (showUser != null){
            return s.error("用户已存在！");
        }else {
            userService.createUser(user);
            return Status.success("true");
        } 
        
    }
    // 用户登录
    @PostMapping("login") // POST请求
    public Status login(@RequestBody User user){
        if (user.getZhanghao() == null || user.getPassword() == null){
            return s.error("账号密码不能为空！");
        }
        User showUser = userService.login(user);
        if (showUser == null){
            return s.error("用户不存在！");
        }else {
            return Status.success(showUser);
        }
    }

}

